using UnityEngine;
using System.Collections;

public class GestureDetector : MonoBehaviour {

	public float PickupSensitivity = 0.3f;
	public float SwipeSensitivity = 1.0f;
	public int timeFrame = 8;
	float yPosPrevFrame = 0;
	float xPosPrevFrame = 0;
	int frameCount = 0;
	
	private float cooldown = 0;
	public float cooldownTime = 1.0f;
	
	void Update () {
		
		WaitBeforeDetectingGestures();
		PickUpGesture();
		SwipeGesture();
	}
	
	void WaitBeforeDetectingGestures() {
		
		OpenNIUserTracker userTracker = GameObject.Find("Sensor").GetComponent<OpenNIUserTracker>();
		
		if ( userTracker.CalibratedUsers.Count >= 1 ) {
			cooldown += Time.deltaTime;
		}
		else {
			cooldown = 0;
		}
	}
	
	void PickUpGesture() {
		
		float yPosThisFrame;
		float velocity = 0;

		yPosThisFrame = this.transform.position.y;
		velocity = yPosThisFrame - yPosPrevFrame;
		yPosPrevFrame = yPosThisFrame;
		
		//Only capture one gesture within a timeframe
		if(frameCount <= timeFrame)
			frameCount++;
		else {
			
			//If velocity is greater than sensitivity send message
			if (velocity > PickupSensitivity) {
				frameCount = 0;
				
				if (cooldown > cooldownTime)
					GameObject.Find("Shade").BroadcastMessage("PickUp", SendMessageOptions.DontRequireReceiver);
			}
		}
	}
	
	void SwipeGesture() {
		
		float xPosThisFrame;
		float velocity = 0;
		
		xPosThisFrame = this.transform.position.x;
		velocity = xPosThisFrame - xPosPrevFrame;
		xPosPrevFrame = xPosThisFrame;
		
		//Only capture one gesture within a timeframe
		if(frameCount <= timeFrame)
			frameCount++;
		else {
			
			//If velocity is greater than sensitivity send message
			if (Mathf.Abs(velocity) > SwipeSensitivity) {
				frameCount = 0;
				
				if (cooldown > cooldownTime) {
				
					if (velocity < 0)
						GameObject.Find("MenuObjects").BroadcastMessage("SwipeRight", SendMessageOptions.DontRequireReceiver);
					else
						GameObject.Find("MenuObjects").BroadcastMessage("SwipeLeft", SendMessageOptions.DontRequireReceiver);
				}
			}
		}
	}
}